package com.cnt.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cnt.dao.UserDao;
import com.cnt.dao.UserInfoDao;
import com.cnt.entity.User;
import com.cnt.entity.UserInfo;
import com.cnt.service.UserService;
import com.cnt.util.LogUtil;
import com.cnt.vo.UserResultVo.LoginResultVo;
import com.cnt.vo.ResultVo;
import com.cnt.vo.UserResultVo.queryUserResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private LogUtil logUtil;

    @Override
    public ResultVo<String> userRegister(User user) {

        LambdaQueryWrapper<User> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(User::getAccount, user.getAccount());
        System.out.println(user);
        List<User> userList = userDao.selectList(lqw1);
        System.out.println(userList);
        if (!userList.isEmpty()) {
            return new ResultVo<>(1, "账号不能重名", null);
        } else {
            LambdaQueryWrapper<User> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(User::getIdCard, user.getIdCard());
            List<User> list = userDao.selectList(lqw2);
            if (!list.isEmpty()) {
                return new ResultVo<>(2, "同一身份证信息不可重复注册,您账号绑定的账号为：" + list.get(0).getAccount(), null);
            }

            int i = userDao.insert(user);
            if (i != 1) {
                return new ResultVo<>(3, "系统繁忙，请稍后重试。", null);
            }
            System.out.println(user.getUserId());

            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(user.getUserId());
            userInfoDao.insert(userInfo);
            logUtil.recordLog(user.getUserId(), user.getAccount() + "注册成功");

            return new ResultVo<>(0, "注册成功", null);
        }
    }


    @Override
    public ResultVo<LoginResultVo> login(String account, String password) {
        User user = userDao.findByAccount(account);
        if (user == null) {
            return new ResultVo<>(1, "找不到此用户", null);
        } else {
            if (user.getLoginFailTimes() >= 8) {
                logUtil.recordLog(user.getUserId(), user.getAccount() + "账号被锁，登录失败");
                return new ResultVo<>(2, "您的账号状态异常，请联系管理员", null);
            }
            if (!Objects.equals(user.getPassword(), password)) {
                userDao.incrementLoginFailTimes(user.getUserId());
                int LoginFailTimes = userDao.findByAccount(account).getLoginFailTimes();
                if (LoginFailTimes == 8) {
                    logUtil.recordLog(user.getUserId(), user.getAccount() + "密码错误8次，账号被锁");
                    return new ResultVo<>(3, "你的账号已经封禁，请联系管理员", null);
                }
                return new ResultVo<>(3, "密码输入错误,还剩下" + (8 - LoginFailTimes) + "次机会", null);
            } else {
                userDao.resetLoginFailTimes(user.getUserId());
                logUtil.recordLog(user.getUserId(), user.getAccount() + "登录成功");
                return new ResultVo<>(0, "登录成功", new LoginResultVo(user.getUserId(), user.getAccount(), user.getName(), user.getUserRole()));
            }

        }

    }


    /**
     * 查询用户信息
     *
     * @param account     账号
     * @param phone       手机号
     * @param queryType   查询类型（0->"查询用户"或1->"查询管理员"）
     * @param queryStatus 用户状态（0->"所有用户"或1->"异常状态用户"）
     * @param querySort   排序方式（0->"用户ID正向排序"、1->"用户ID逆向排序"、2->"慈善积分正向排序"、3->"慈善积分逆向排序"）
     * @return 用户列表
     */
    public List<queryUserResultVo> queryUser(String account, String phone, Integer queryType, Integer queryStatus, Integer querySort) {
        return userDao.queryUser(account, phone, queryType, queryStatus, querySort);
    }

    public ResultVo<String> changePassword(String account, String idCard, String newPassword) {
        System.out.println(account + "+" + idCard + "+" + newPassword);
        User user = userDao.findByAccount(account);
        if (user == null) {
            return new ResultVo<String>(1, "找不到该账号", null);
        }
        if (!user.getIdCard().equals(idCard)) {
            return new ResultVo<String>(2, "身份信息有误", null);
        }
        if (user.getLoginFailTimes() >= 8) {
            logUtil.recordLog(user.getUserId(), user.getAccount() + "账号被锁，修改密码失败");
            return new ResultVo<String>(3, "账号状态异常，请联系管理员", null);
        }
        user.setPassword(newPassword);
        int i = userDao.updateById(user);
        logUtil.recordLog(user.getUserId(), user.getAccount() + "修改密码成功，新密码为");
        return new ResultVo<>(i == 1 ? 0 : 4, "修改密码成功", null);
    }

    //改变用户权限
    @Override
    public ResultVo changeUserRole(Integer userId, Integer operatorId) {
        User user = userDao.selectById(userId);
        User operatorUser = userDao.selectById(operatorId);
        if (user.getUserRole() == 0) {
            user.setUserRole(1);
            if (userDao.updateById(user) == 1) {
                logUtil.recordLog(operatorUser.getUserId(), operatorUser.getAccount() + "将" + "id为" + user.getUserId() + "的" + user.getAccount() + "设置为管理员");
                logUtil.recordLog(user.getUserId(), user.getAccount() + "被设置为管理员");
                return new ResultVo(0, "添加管理员成功", null);
            }
        } else if (user.getUserRole() == 1) {
            user.setUserRole(0);
            if (userDao.updateById(user) == 1) {
                logUtil.recordLog(operatorUser.getUserId(), operatorUser.getAccount() + "将" + "id为" + user.getUserId() + "的" + user.getAccount() + "撤销了管理员权限");
                logUtil.recordLog(user.getUserId(), user.getAccount() + "被撤销了管理员权限");
                return new ResultVo(0, "撤销管理员成功", null);
            }
        }
        return new ResultVo(1, "更改管理员权限状态失败", null);
    }

    @Override
    public ResultVo deleteUserById(Integer userId, Integer operatorId) {
        User user = userDao.selectById(userId);
        User operatorUser = userDao.selectById(operatorId);
        if (user == null) {
            return new ResultVo(3, "不可删除不存在的用户", null);
        }
        if (user.getUserRole() == 1) {
            return new ResultVo(2, "请撤销管理员之后再进行删除操作", null);
        }
        if (userDao.deleteById(userId) == 1) {
            logUtil.recordLog(operatorUser.getUserId(), operatorUser.getAccount() + "将" + "id为" + user.getUserId() + "的" + user.getAccount() + "删除了");
            logUtil.recordLog(user.getUserId(), user.getAccount() + "被删除了");
            return new ResultVo(0, "删除用户成功", null);
        } else {
            return new ResultVo(1, "删除用户失败", null);
        }
    }

    @Override
    public ResultVo updateUserStatus(Integer userId, Integer operatorId) {
        User operatorUser = userDao.selectById(operatorId);
        User user = userDao.selectById(userId);
        if (user.getLoginFailTimes() >= 8) {
            user.setLoginFailTimes(0);
            if (userDao.updateById(user) == 1) {
                logUtil.recordLog(operatorUser.getUserId(), operatorUser.getAccount() + "将" + "id为" + user.getUserId() + "的" + user.getAccount() + "删除了");
                logUtil.recordLog(user.getUserId(), user.getAccount() + "被解封了");
                return new ResultVo(0, "解封账号成功", null);
            }

        } else if (user.getLoginFailTimes() < 8) {
            user.setLoginFailTimes(8);
            if (userDao.updateById(user) == 1) {
                logUtil.recordLog(operatorUser.getUserId(), operatorUser.getAccount() + "将" + "id为" + user.getUserId() + "的" + user.getAccount() + "封锁了");
                logUtil.recordLog(user.getUserId(), user.getAccount() + "被封锁了");
                return new ResultVo(0, "封锁账号成功", null);
            }

        }
        return new ResultVo(1, "修改用户状态失败", null);
    }

    @Override
    public ResultVo<String> checkAccount(String account) {
        User user = userDao.findByAccount(account);
        if (user != null) return new ResultVo<>(1, "账号不能重名", null);
        return new ResultVo<>(0, "", null);
    }

    @Override
    public ResultVo<String> checkIdCard(String idCard) {
        LambdaQueryWrapper<User> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(User::getIdCard, idCard);
        List<User> list = userDao.selectList(lqw2);
        if (!list.isEmpty()) {
            return new ResultVo<>(2, "同一身份证信息不可重复注册,您账号绑定的账号为：" + list.get(0).getAccount(), null);
        }
        return new ResultVo<>(0, "", null);
    }

    @Override
    public ResultVo<String> cancelAccount(Integer userId, String account, String IdCard) {
        User user = userDao.selectById(userId);
        int delete = 0;
        System.out.println(account);
        System.out.println(IdCard);
        System.out.println(user);
        if (user == null) new ResultVo<>(1, "找不到该用户", null);
        else if (!user.getAccount().equals(account)) {
            return new ResultVo<>(2, "账号错误", null);
        } else if (!user.getIdCard().equals(IdCard)) {
            return new ResultVo<>(3, "信息填写错误", null);
        } else delete = userDao.deleteById(user.getUserId());
        if (delete == 0) return new ResultVo<>(4, "注销失败", null);
        return new ResultVo<>(0, "注销成功", null);
    }

}

